package com.md.youyouhui.utils.calladapter;

import android.arch.core.util.Function;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.MainThread;

import com.md.youyouhui.common.Resource;
import com.md.youyouhui.net.Result;

/**
 * Created by AdministratorZJ
 * on 2018/7/31.
 */

public class ResourceConvertUtils {

    @Deprecated
    @MainThread
    public static <T> LiveData<Resource<Result<T>>> convert(LiveData<Result<T>> source) {
        MutableLiveData<Resource<Result<T>>> map = LiveDataTransformations.map(source, new Function<Result<T>, Resource<Result<T>>>() {
            @Override
            public Resource<Result<T>> apply(Result<T> input) {
                if (input.code == 0) {
                    return Resource.success(input);
                } else {
                    return Resource.error(input.code, input.msg, input);
                }
            }
    });
        map.setValue(Resource.loading(null));
        return map;
    }

    @MainThread
    public static <T> LiveData<Resource<T>> convertResource(LiveData<Result<T>> source) {
        MutableLiveData<Resource<T>> map = LiveDataTransformations.map(source, input -> {
            if (input.code == 0) {
                return Resource.success(input.data);
            } else {
                return Resource.error(input.code, input.msg, input.data);
            }
        });
        map.setValue(Resource.loading(null));
        return map;
    }

}
